package com.weiai.wedding.web.cases;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.weiai.wedding.entity.cases.Resources;
import com.weiai.wedding.service.ServiceException;
import com.weiai.wedding.service.cases.ResourcesService;
import com.weiai.wedding.util.ConUtils;
import com.weiai.wedding.util.DataTablesParamUtility;
import com.weiai.wedding.util.DataTablesReturnObject;
/**
 * 资源管理控制器
 * @author wangweiheng
 *
 */
@Controller
@RequestMapping(value="/cases/resources")
public class ResourcesController {
	
	@Autowired
	private ResourcesService resourcesService;
	
	@RequestMapping(value="")
	public String list(Model model){
		return "cases/resources/resourcesList";
	}
	
	@RequestMapping(value="list")
	@ResponseBody
	public DataTablesReturnObject<Resources> query(Model model,Resources resources,HttpServletRequest req){
		Sort sort = new Sort(Direction.DESC, "resourcesId");
		Pageable pageable = DataTablesParamUtility.buildPage(req,sort);
		String sEcho = req.getParameter("sEcho");
		String resourcesName = resources.getResourcesName();
		DataTablesReturnObject<Resources> dataTablesReturnObject = new DataTablesReturnObject();
		if(resourcesName==null || "".equals(resourcesName)){
			Page<Resources> page = resourcesService.getAll(pageable);
			dataTablesReturnObject = DataTablesParamUtility.toDataTablesReturnObject(sEcho, page);
		}else{
			Page<Resources> page = resourcesService.getAllByName(resourcesName,pageable);
			dataTablesReturnObject = DataTablesParamUtility.toDataTablesReturnObject(sEcho, page);
		}
		return dataTablesReturnObject;
	}
	
	@RequestMapping(value="pop/{id}")
	public String pop(@PathVariable("id") Long id,Model model){
		model.addAttribute("pop","1");
		model.addAttribute("serial", id);
		return "cases/resources/resourcesList";
	}
	
	@RequestMapping(value="create")
	public String createForm(Model model){
		model.addAttribute("resources",new Resources());
		model.addAttribute("actionId","1");//新增时候页面判断使用
		return "cases/resources/resourcesForm";
	}
	
	@RequestMapping("update/{id}")
	public String updateForm(@PathVariable("id") Long id,Model model){
		Resources resources = resourcesService.getResources(id);
		model.addAttribute("resources",resources);
		model.addAttribute("actionId","2");//修改时候页面判断使用
		return "cases/resources/resourcesForm";
	}
	
	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id")Long id,
			RedirectAttributes redirectAttributes){
		resourcesService.deleteResources(id);
		redirectAttributes.addFlashAttribute("message","删除资源成功"); 
		return "redirect:/cases/resources";
	}
	
	@RequestMapping(value = "save")
	public String save(Resources po,@RequestParam MultipartFile file,
			RedirectAttributes redirectAttributes){
		if(file==null || file.getSize()==0){
			throw new ServiceException("文件内容为空！请重新上传");
		}
		String fileName = ConUtils.formatDate(new Date(),"yyMMddHHmmss")+file.getOriginalFilename();
		try {
			InputStream is = file.getInputStream();
			resourcesService.saveResources(po, fileName, is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		redirectAttributes.addFlashAttribute("message","添加资源成功");
		return "redirect:/cases/resources";
	}
	
	@RequestMapping(value = "update")
	public String update(Resources po,@RequestParam MultipartFile file,
			RedirectAttributes redirectAttributes){
		if(file==null || file.getSize()==0){
			throw new ServiceException("文件内容为空！请重新上传");
		}
		
		String fileName = file.getOriginalFilename();
		try {
			InputStream is = file.getInputStream();
			resourcesService.updateResources(po, fileName, is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		redirectAttributes.addFlashAttribute("message","修改资源成功");
		return "redirect:/cases/resources";
	}

	@RequestMapping(value = "viewPhoto/{id}")
	public void getPhotoById (@PathVariable("id")Long id,HttpServletResponse response){   
	    Resources resources = resourcesService.getResources(id); 
	    String path = resources.getResourcesDir();
	    response.setContentType("image/jpeg");   
	    response.setCharacterEncoding("UTF-8");   
	    OutputStream outputSream;
	    FileInputStream is;
		try {
			outputSream = response.getOutputStream();
			is = new FileInputStream (path);
			int len = 0;   
		    byte[] buf = new byte[1024];   
		    while ((len = is.read(buf, 0, 1024)) != -1) {   
		        outputSream.write(buf, 0, len);   
		    }   
		    outputSream.close();
		    is.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}  

}
